package com.example.event_resource_java.commons.Interception;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.example.event_resource_java.authority.server.UserServer;
import com.example.event_resource_java.commons.exce.JinZhiException;
import com.example.event_resource_java.commons.util.ApiResult;
import com.example.event_resource_java.commons.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
public class LoginInterception implements HandlerInterceptor {

    @Autowired
    private UserServer user;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取token
        String requestURI = request.getRequestURI();
        System.out.println("preHandle拦截的请求路径是: " + requestURI);
        String authorization = request.getHeader("Authorization");
        System.out.println(authorization);
//        if (ObjectUtil.isEmpty(authorization)) {
//            returnNoLogin(response, "请先登录");
//            return false;
//        }

        try {
//            UserDO onlineUser = JWTUtil.getUser();
            JWTUtil.jzverify(authorization);
//            onlineUser.getUsername();
        }catch (JinZhiException e) {
            returnNoLogin(response, e.getMsg());
            return false;
        }

        return true;
    }

    /**
     * 返回未登录的错误信息
     * @param response ServletResponse
     */
    private void returnNoLogin(HttpServletResponse response, String message) throws IOException {

        ServletOutputStream outputStream = response.getOutputStream();
        // 设置返回401 和响应编码
        response.setStatus(200);
        response.setContentType("Application/json;charset=utf-8");
        // 构造返回响应体
        ApiResult<Object> result = new ApiResult<>();
        result.setCode(401001);
        result.setMsg(message);
//        result.setMsg(message);
        String resultString = JSONUtil.toJsonStr(result);
        outputStream.write(resultString.getBytes(StandardCharsets.UTF_8));

    }

}
